/**
 * 高级PDF导出功能
 * 使用html2canvas和jsPDF生成高质量PDF
 */

export const useAdvancedPdfExport = () => {
  /**
   * 使用html2canvas和jsPDF导出PDF
   * @param element 要导出的DOM元素
   * @param filename 文件名
   */
  const exportToPdfAdvanced = async (element: HTMLElement, filename: string = 'resume.pdf') => {
    try {
      // 动态导入库
      const html2canvas = (await import('html2canvas')).default
      const jsPDF = (await import('jspdf')).default

      // 临时修改元素样式以占满页面宽度
      const originalMaxWidth = element.style.maxWidth
      const originalWidth = element.style.width
      const originalMargin = element.style.margin
      
      element.style.maxWidth = '100%'
      element.style.width = '100%'
      element.style.margin = '0'
      
      // 设置导出选项
      const canvas = await html2canvas(element, {
        scale: 2, // 提高清晰度
        useCORS: true,
        allowTaint: true,
        backgroundColor: '#ffffff',
        logging: false,
        width: element.scrollWidth,
        height: element.scrollHeight,
        scrollX: 0,
        scrollY: 0,
        windowWidth: element.scrollWidth,
        windowHeight: element.scrollHeight
      })
      
      // 恢复原始样式
      element.style.maxWidth = originalMaxWidth
      element.style.width = originalWidth
      element.style.margin = originalMargin

      // 创建PDF
      const imgData = canvas.toDataURL('image/png', 1.0)
      const pdf = new jsPDF({
        orientation: 'portrait',
        unit: 'mm',
        format: 'a4'
      })

      // 计算PDF尺寸，确保占满整个页面宽度
      const pdfWidth = pdf.internal.pageSize.getWidth()
      const pdfHeight = pdf.internal.pageSize.getHeight()
      const imgWidth = canvas.width
      const imgHeight = canvas.height
      
      // 以宽度为准，确保占满整个页面宽度
      const ratio = pdfWidth / imgWidth
      const imgX = 0 // 从左边开始，不居中
      const imgY = 0
      const finalHeight = imgHeight * ratio

      // 如果内容超过一页，需要分页处理
      if (finalHeight > pdfHeight) {
        // 计算需要多少页
        const totalPages = Math.ceil(finalHeight / pdfHeight)
        
        for (let i = 0; i < totalPages; i++) {
          if (i > 0) {
            pdf.addPage()
          }
          
          const yOffset = -i * pdfHeight
          pdf.addImage(imgData, 'PNG', imgX, yOffset, pdfWidth, finalHeight)
        }
      } else {
        // 单页内容，直接添加
        pdf.addImage(imgData, 'PNG', imgX, imgY, pdfWidth, finalHeight)
      }

      // 保存PDF
      pdf.save(filename)

      return true
    } catch (error) {
      console.error('高级PDF导出失败:', error)
      throw error
    }
  }

  /**
   * 检查是否支持高级PDF导出
   */
  const isAdvancedPdfSupported = async (): Promise<boolean> => {
    try {
      await import('html2canvas')
      await import('jspdf')
      return true
    } catch {
      return false
    }
  }

  return {
    exportToPdfAdvanced,
    isAdvancedPdfSupported
  }
}
